from PyQt5.QtWidgets import QMainWindow
from view import Ui_Window
from function import Select
import random as rd
import numpy as np
import re


class MyWindow(QMainWindow, Ui_Window):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setupUi(self)
        self.array = None
        self.createdata.clicked.connect(self.RandomData)
        self.runButton.clicked.connect(self.run)

        self.setWindowTitle("线性时间选择")
        self.input_data.setPlaceholderText("请输入以非数字相关字符隔开的实数序列再点击确定")
        self.regx = re.compile("([+-]?[0-9]+(\.[0-9]+)?)")

    def RandomData(self):
        tmp_size = rd.randint(2, 300)
        # tmp_size = 5
        tmp_array = np.empty([tmp_size], dtype=int)
        show_str = ','.join([str(x) for x in tmp_array])
        self.input_data.setPlainText(show_str)

    def run(self):
        in_text = self.input_data.toPlainText()
        tmp = self.regx.findall(in_text)
        self.array = [float(x[0]) for x in tmp]
        if self.array == []:
            self.output_data.setPlainText("请先输入")
        select_way = self.select_way.currentIndex()  # 0或1
        k = int(self.getk.text())
        if k > len(self.array):
            self.output_data.setPlainText("k值过大" + "\n数组长度: " + str(len(self.array)))
            return
        if select_way == 1:
            k = len(self.array) + 1 - k
        ans = self.array[Select(self.array, 0, len(self.array) - 1, k)]
        self.output_data.setPlainText("输出结果:\t" + str(ans) + "\n数组长度: " + str(len(self.array)))
